# -*- coding: utf-8 -*-
import datetime
import json
import logging.config

from conf.config import BEANSTALKD_HOST, BEANSTALKD_PORT, BEANSTALKD_TUBE
from conf.logging import LOGGING_DICT_CONFIG
from lib import beanstalkc
from util.json_util import JSONEncoder

logger = logging.getLogger("wechat.beanstalkd")


def add_mq_task(trade_no, message_type, delay=172800):
    """
    往beanstalk消息队列中写入消息
    :param trade_no: 订单号
    :param message_type: 消息类型（1=微信支付对账，2=礼品订单退款，3=计算收益，4=7天后确认收货，5=修改优惠券状态，6=门店订单自动收货）
    :param delay: 延迟时间(单位秒)，微信支付订单 5分钟后检查一次，2礼品订单48小时检查
    :return:
    """
    jid = None
    try:
        doc_b = {
            'trade_no': trade_no,
            'message_type': message_type,
            'create_date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        beanst = beanstalkc.Connection(host=BEANSTALKD_HOST, port=BEANSTALKD_PORT, connect_timeout=10)
        beanst.use(BEANSTALKD_TUBE)
        # 延迟队列
        jid = beanst.put(json.dumps(doc_b), delay=delay)
        logger.debug(f"add_mq_task: jid={jid}, trade_no={trade_no}, message_type={message_type}")
        beanst.close()
    except Exception as e:
        logger.error(f"add_mq_task: 消息队列添加失败：trade_no={trade_no},message_type={message_type},delay={delay}")
        logger.exception(e)
    return jid


def add_mq_cash_task(open_id, cash_method, agency_uid, fee, name, ip, delay=0):
    """
    新增提现任务

    :param open_id:
    :param cash_method: 提现方式
    :param agency_uid: 合伙人UID，普通用户提现为""
    :param fee: 提现金额
    :param name: 实名
    :param ip: IP
    :param delay: 延时
    :return:
    """

    jid = None
    doc_b = {
        'open_id': open_id,
        'cash_method': cash_method,
        'agency_uid': agency_uid,
        'fee': fee,
        'name': name,
        'ip': ip,
        'create_date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    }
    try:

        beanst = beanstalkc.Connection(host=BEANSTALKD_HOST, port=BEANSTALKD_PORT, connect_timeout=10)
        beanst.use("cash_apply")
        # 延迟队列
        jid = beanst.put(json.dumps(doc_b, cls=JSONEncoder), delay=delay)
        logger.debug(f"add_mq_cash_task: 提现 jid={jid}")
        beanst.close()
    except Exception as e:
        logger.error(f"add_mq_cash_task: 消息队列添加失败：doc={doc_b}")
        logger.exception(e)
    return jid


def add_mq_reward_task(agency_uid, delay=518400):
    """
    增加延时任务：延时6小时给发卡人激励

    :param agency_uid:
    :param delay:
    :return:
    """
    jid = None
    doc_b = {
        'agency_uid': agency_uid,
        'create_date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    }
    try:
        beanst = beanstalkc.Connection(host=BEANSTALKD_HOST, port=BEANSTALKD_PORT, connect_timeout=10)
        beanst.use("reward_agency")
        # 延迟队列
        jid = beanst.put(json.dumps(doc_b, cls=JSONEncoder), delay=delay)
        logger.debug(f"add_mq_reward_task: jid={jid} reward_agency_uid={agency_uid}")
        beanst.close()
    except Exception as e:
        logger.error(f"add_mq_reward_task: 消息队列添加失败：doc={doc_b}")
        logger.exception(e)
    return jid


def add_mq_send_card_task(open_id, delay=72000):
    """
    增加延时任务：延时20小时给发体验卡

    :param open_id:
    :param delay:
    :return:
    """
    jid = None
    doc_b = {
        'open_id': open_id,
        'create_date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    }
    try:
        beanst = beanstalkc.Connection(host=BEANSTALKD_HOST, port=BEANSTALKD_PORT, connect_timeout=10)
        beanst.use("send_card")
        # 延迟队列
        jid = beanst.put(json.dumps(doc_b, cls=JSONEncoder), delay=delay)
        logger.debug(f"add_mq_send_card_task: jid={jid} open_id={open_id}")
        beanst.close()
    except Exception as e:
        logger.error(f"add_mq_send_card_task: 消息队列添加失败：doc={doc_b}")
        logger.exception(e)
    return jid


def mq_status(jid=None):
    """
    查看统计信息
    :return:
    """
    try:
        beanst = beanstalkc.Connection(host=BEANSTALKD_HOST, port=BEANSTALKD_PORT)
        stats = beanst.stats()
        logger.debug(stats.decode())
        stats_tube = beanst.stats_tube(BEANSTALKD_TUBE)
        logger.debug(stats_tube.decode())
        if jid:
            stats_job = beanst.stats_job(jid)
            logger.debug(stats_job.decode())
        beanst.close()
    except Exception as e:
        logger.exception(e)
        pass


if __name__ == "__main__":
    logging.config.dictConfig(LOGGING_DICT_CONFIG)
    j = add_mq_task("15029452095945933", message_type=2, delay=3)
    mq_status(j)
    pass
